//
//  BKDropMenu.m
//  iLookForiPhone
//
//  Created by Zhang Yinghui on 12-8-23.
//  Copyright (c) 2012年 LavaTech. All rights reserved.
//

#import "BKDropMenu.h"
#import "BKKit.h"
#import "UIWindow+x.h"
#import "BKLineView.h"

#define DROP_MENU_ARROW_HEIGHT 11.0f
#define DROP_MENU_CONTENT_PADDING 3.0f

#define ITEM_ODD_BG_COLOR [UIColor colorWithWhite:0.9 alpha:1.0]
#define ITEM_EVEN_BG_COLOR [UIColor colorWithWhite:0.925 alpha:1.0]
#define ITEM_TITLE_COLOR [UIColor blackColor]
#define ITEM_TITLE_COLOR_HIGHLIGHTED [UIColor colorWithRed:0.08 green:0.49 blue:0.98 alpha:1.00]
#define ITEM_VER_MARGIN 2.0f

@interface BKDropMenuBackground:UIView
@property (nonatomic, assign) CGPoint anchorPoint;
@end

@interface BKDropMenu()
@property (nonatomic, retain) UIScrollView *contentView;
@property (nonatomic, retain) BKDropMenuBackground *backgroundView;
@property (nonatomic, assign) NSInteger validCount;
@end

@implementation BKDropMenu
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (id)initWithItems:(NSArray *)items anchorView:(UIView *)anchorView delegate:(id<BKDropMenuDelegate>)delegate{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (self = [super initWithFrame:window.bounds]) {
        self.anchorView = anchorView;
        self.delegate = delegate;
        self.backgroundColor = [UIColor clearColor];
        self.itemHeight = 32;
        self.menuWidth = 100;
        
        _backgroundView = [[BKDropMenuBackground alloc] initWithFrame:CGRectZero];
        [self addSubview:_backgroundView];
        _contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 100, 0)];
        [_contentView setAlwaysBounceVertical:YES];
        _contentView.layer.cornerRadius = 5.0f;
        _contentView.clipsToBounds = YES;
        [_backgroundView addSubview:_contentView];
        
        
        [_backgroundView.layer setShadowColor:[UIColor colorWithWhite:0 alpha:0.3].CGColor];
        [_backgroundView.layer setShadowRadius:1.0];
        [_backgroundView.layer setShadowOpacity:0.8];
        [_backgroundView.layer setShadowOffset:CGSizeMake(0, 0)];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotate:) name:UIDeviceOrientationDidChangeNotification  object:[UIDevice currentDevice]];
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSInteger i = 0, n = [items count]; i < n; i++) {
            id item = [items objectAtIndex:i];
            if ([item isKindOfClass:[NSDictionary class]]) {
                id enabled = [item valueForKey:@"enabled"];
                item = [[BKDropMenuItem alloc] initWithTitle:[item valueForKey:@"title"] data:[item valueForKey:@"data"]];
               ( (BKDropMenuItem *)item).enabled = enabled?[enabled boolValue] : YES;
                
            }
            if ([item isKindOfClass:[BKDropMenuItem class]]) {
                [arr addObject:item];
            }
        }
        self.items = arr;
        [self createItemViews];
        self.anchorOffset = CGPointMake(self.anchorView.bounds.size.width/2, self.anchorView.bounds.size.height);
    }
    return self;
}
- (void)addTarget:(id)target action:(SEL)action{
    self.target = target;
    self.action = action;
}
/**
 *  计算contentView 高度
 *
 */
- (float)heightForContentView{
    float h = 0;
    NSInteger n = [self.items count];
    NSInteger maxVisibleItems = 0;
    for (int i=0; i<n; i++) {
        if (maxVisibleItems >= 6) {
            break;
        }
        BKDropMenuItem *item = [self.items objectAtIndex:i];
        if (!item.enabled) {
            continue;
        }
        h += maxVisibleItems > 0 ? ITEM_VER_MARGIN : 0;
        
        if (item.title) {
            h += self.itemHeight;
        }else{
            h += 2;
        }
        maxVisibleItems ++;
    }
    return h;
}
/**
 *  调整界面 先把背景 backgroundView  以及contentView frame 调整好
 *
 */
- (void)relayoutBackground{
    if ( !self.items || self.items.count == 0 ) {
        return;
    }
    //arrow location
    CGPoint arrowPoint = [self convertPoint:self.anchorOffset fromView:self.anchorView];
    
    float x = MAX(arrowPoint.x - self.menuWidth/2, 10);
    float y = arrowPoint.y;
    if((x+self.menuWidth) > self.bounds.size.width){
        x = self.bounds.size.width - self.menuWidth-10;
    }
    
    float h = [self heightForContentView]+DROP_MENU_ARROW_HEIGHT+2*DROP_MENU_CONTENT_PADDING;
    
    [self.backgroundView setAnchorPoint:CGPointMake(arrowPoint.x - x, 0)];
    [self.backgroundView setFrame:CGRectMake(x, y, self.menuWidth, h)];
    
    CGRect rect = CGRectInset(self.backgroundView.bounds, DROP_MENU_CONTENT_PADDING, DROP_MENU_CONTENT_PADDING);
    rect.origin.y += DROP_MENU_ARROW_HEIGHT;
    rect.size.height -= DROP_MENU_ARROW_HEIGHT;
    [self.contentView setFrame:rect];
}
/**
 *  创建界面 每一个条目
 *
 */
- (void)createItemViews{
    [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    if ( !self.items || self.items.count == 0 ) {
        return;
    }
    int validCount = 0;
    CGRect itemFrame = CGRectMake(0, 0, self.contentView.bounds.size.width, 0);
    for (int i=0; i<self.items.count; i++) {
        BKDropMenuItem *item = [self.items objectAtIndex:i];
        if (!item.enabled) {
            continue;
        }
        if (item.title) {
            itemFrame.size.height = self.itemHeight;
            UIButton *btn = [[UIButton alloc] initWithFrame:itemFrame];
            btn.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [btn setTag:i];
            btn.backgroundColor = validCount%2 == 0? ITEM_ODD_BG_COLOR : ITEM_EVEN_BG_COLOR;
            
            [btn setTitleColor:ITEM_TITLE_COLOR forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            [btn setTitleColor:ITEM_TITLE_COLOR_HIGHLIGHTED forState:UIControlStateHighlighted];
            
            [btn addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:[item.title uppercaseString] forState:UIControlStateNormal];
            [self.contentView addSubview:btn];
            validCount ++ ;
        }
        if (!item.title) {
            if (validCount == 0) {
                continue;
            }
            itemFrame.size.height = 2;
            UIView *line = [[UIView alloc] initWithFrame:itemFrame];
            line.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
            [self.contentView addSubview:line];
        }
        itemFrame.origin.y += itemFrame.size.height+ITEM_VER_MARGIN;
    }
    self.validCount = validCount;
    [self.contentView setContentSize:CGSizeMake(0, itemFrame.origin.y - ITEM_VER_MARGIN)];
}
//- (void)setItems:(NSArray *)items{
//    NSMutableArray *arr = [NSMutableArray array];
//    for (NSInteger i = 0, n = [items count]; i < n; i++) {
//        id item = [items objectAtIndex:i];
//        if ([item isKindOfClass:[NSDictionary class]]) {
//            item = [[BKDropMenuItem alloc] initWithDictionary:item];
//        }
//        [arr addObject:item];
//    }
//    ////
//    _items = arr;
//    [self relayoutBackground];
//    [self setup];
//}
//- (void)setFilterItem:(id)filterItem{
//    ////
//    _filterItem = filterItem ;
//    [self relayoutBackground];
//    [self setup];
//}
- (void)selectedItem:(id)btn{
    NSInteger i = [btn tag];
    id item = [self.items objectAtIndex:i];
    DLOG(@"%@",self.delegate);
    if (self.delegate && [self.delegate respondsToSelector:@selector(dropMenu:didSelectItem:)]) {
        [self.delegate dropMenu:self didSelectItem:item];
    }
    if (self.target && self.action) {
//        [self.target performSelector:self.action withObject:self withObject:item];
        
        IMP imp = [self.target methodForSelector:self.action];
        void (*func)(id, SEL, NSObject *) = (void *)imp;
        func(self.target, self.action, item);
    }
    [self close];
}
- (void)show{
    if ( self.validCount > 0) {
        
        UIWindow *window = [UIWindow popWindow];
        if (!self.superview) {
            [window addSubview:self];
        }
        float angle = 0;
        if ([APP statusBarOrientation] == UIInterfaceOrientationLandscapeRight) {
            angle = M_PI*0.5;
        }
        if([APP statusBarOrientation] == UIInterfaceOrientationLandscapeLeft){
            angle = -M_PI*0.5;
        }
        self.bounds = window.bounds;
        self.center = window.center;
        if (angle!=0) {
            self.transform = CGAffineTransformMakeRotation(angle);
        }
        
        //[[UIApplication sharedApplication] setStatusBarOrientation:orientation];
        
        [self relayoutBackground];
        
        [self setHidden:NO];
        [window makeKeyAndVisible];
    }
}
- (void)close{
    if([self superview]){
        [self setHidden:YES];
        [self removeFromSuperview];
    }
    
    [UIWindow popWindow].hidden = YES;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self close];
}
- (void)deviceRotate:(NSNotification *)noti  {
    UIInterfaceOrientation orientation = [APP statusBarOrientation];
    switch (orientation) {
        case UIDeviceOrientationPortrait:
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            break;
        case UIDeviceOrientationLandscapeLeft: //home button on the right
        case UIDeviceOrientationLandscapeRight:{
            float angle = M_PI*0.5;
            if(orientation == UIDeviceOrientationLandscapeRight){
                angle = -M_PI*0.5;
            }
            [UIView animateWithDuration:0.8
                             animations:^{
                                 self.transform = CGAffineTransformMakeRotation(angle);
                             }
                             completion:^(BOOL finished) {
                             }];
            break;
            
        }
        default:
            break;
    }
}

+ (instancetype)dropMenuWithItems:(NSArray *)items anchorView:(UIView *)anchorView delegate:(id<BKDropMenuDelegate>)delegate{
    BKDropMenu *menu = [[BKDropMenu alloc] initWithItems:items anchorView:anchorView delegate:delegate];
    return menu;
}
@end

@implementation BKDropMenuBackground
- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
- (void)setAnchorPoint:(CGPoint)anchorPoint{
    _anchorPoint = anchorPoint;
    [self setNeedsDisplay];
}
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect{
    float x1 = self.anchorPoint.x;
    float y1 = 0;
    CGRect r = rect;
	float minx = CGRectGetMinX(r), midx = CGRectGetMidX(r), maxx = CGRectGetMaxX(r);
	float miny = CGRectGetMinY(r)+DROP_MENU_ARROW_HEIGHT, midy = CGRectGetMidY(r), maxy = CGRectGetMaxY(r);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGContextSetFillColorWithColor(ctx, [UIColor colorWithWhite:1.0 alpha:1.0].CGColor);
    CGContextMoveToPoint(ctx, minx, midy);
    int rad = 5.0;
	CGContextAddArcToPoint(ctx, minx, miny, x1-7, miny, rad);
    CGContextAddLineToPoint(ctx, x1-7, miny);
    CGContextAddLineToPoint(ctx, x1, y1);
    CGContextAddLineToPoint(ctx, x1+7, miny);
	CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, rad);
	CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, rad);
	CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, rad);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);
    CGContextRestoreGState(ctx);
}
@end


@implementation BKDropMenuItem
- (id)initWithTitle:(NSString *)title data:(id)data{
    if (self = [super init]) {
        self.title = title;
        self.data = data;
        self.enabled = YES;
    }
    return self;
}
@end
